import React, { useEffect, useState, useRef } from 'react';
import { useSelector } from 'react-redux';
import type { RootState } from '../store';

interface ThemeProviderProps {
  children: React.ReactNode;
}

const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
  const themeMode = useSelector((state: RootState) => state.theme.mode);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [previousTheme, setPreviousTheme] = useState<string>('');
  const overlayRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // 确保主题在组件挂载时正确设置
    document.body.setAttribute('data-theme', themeMode);
  }, [themeMode]);

  useEffect(() => {
    // 主题切换时的动画效果
    if (themeMode && previousTheme && themeMode !== previousTheme) {
      setIsTransitioning(true);
      
      // 创建覆盖层元素
      const overlay = document.createElement('div');
      overlay.className = 'theme-transition-overlay';
      
      // 设置覆盖层的背景色为新主题的背景色
      const newBgColor = themeMode === 'dark' ? '#141414' : '#ffffff';
      overlay.style.background = newBgColor;
      
      document.body.appendChild(overlay);
      
      // 添加全局过渡动画类
      document.body.classList.add('theme-transitioning');
      
      // 触发环形扩散动画
      requestAnimationFrame(() => {
        overlay.classList.add('active');
      });
      
      // 动画完成后清理
      setTimeout(() => {
        document.body.classList.remove('theme-transitioning');
        if (overlay.parentNode) {
          overlay.parentNode.removeChild(overlay);
        }
        setIsTransitioning(false);
      }, 600);
    }
    
    setPreviousTheme(themeMode);
  }, [themeMode, previousTheme]);

  return <>{children}</>;
};

export default ThemeProvider; 